/*
 ***** BEGIN LICENSE BLOCK *****
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is BS1.
 *
 * The Initial Developer of the Original Code is SpaceMan.
 * Portions created by SpaceMan are Copyright (C) 2009
 * SpaceMan. All Rights Reserved.
 *
 * Contributor(s):
 * SpaceMan <sandaimespaceman@gmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU Public License (the "GPL License"), in which case the
 * provisions of MPL License are applicable instead of those
 * above. If you wish to allow use of your version of this file only
 * under the terms of the GPL License and not to allow others to use
 * your version of this file under the MPL, indicate your decision by
 * deleting the provisions above and replace them with the notice and
 * other provisions required by the GPL License. If you do not delete
 * the provisions above, a recipient may use your version of this file
 * under either the MPL or the GPL License.
 ***** END LICENSE BLOCK *****
 */
package com.uniteduniverse.apps.bs1ide;

import com.uniteduniverse.libs.BrainSpace1.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;

/**
 * The BS1IDE's main GUI.
 * @version 1.0
 * @author SpaceMan
 */
public class BS1IDEView extends javax.swing.JFrame
{
	/** Creates new form BS1IDEView */
	public BS1IDEView()
	{
		initComponents();
	}

	/**
	 * Update all status windows
	 */
	public void Update()
	{
		updateTable();
		updateDebugStatus();
		updateStatus();
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        HelpDialog = new javax.swing.JDialog();
        HelpScrollPane = new javax.swing.JScrollPane();
        HelpView = new javax.swing.JEditorPane();
        Toolbars = new javax.swing.JPanel();
        FileToolbar = new javax.swing.JToolBar();
        NewToolbarBtn = new javax.swing.JButton();
        OpenToolbarBtn = new javax.swing.JButton();
        DownloadToolbarBtn = new javax.swing.JButton();
        SaveToolbarBtn = new javax.swing.JButton();
        SaveAsToolbarBtn = new javax.swing.JButton();
        DebugToolbar = new javax.swing.JToolBar();
        GoToolbarBtn = new javax.swing.JButton();
        DebugToolbarBtn = new javax.swing.JButton();
        ToolbarSep1 = new javax.swing.JToolBar.Separator();
        ContinueBtn = new javax.swing.JButton();
        NextStepBtn = new javax.swing.JButton();
        SettingsToolbar = new javax.swing.JToolBar();
        ToolbarLabel1 = new javax.swing.JLabel();
        BreakpointChar = new javax.swing.JFormattedTextField();
        SetToolbarBtn = new javax.swing.JButton();
        ResetToolbarBtn = new javax.swing.JButton();
        HelpToolbar = new javax.swing.JToolBar();
        HelpToolbarBtn = new javax.swing.JButton();
        AboutToolbarBtn = new javax.swing.JButton();
        MainPane = new javax.swing.JSplitPane();
        Workspace = new javax.swing.JTabbedPane();
        EditorPane = new javax.swing.JScrollPane();
        SrcEditor = new javax.swing.JTextArea();
        DebugViewerScrollPane = new javax.swing.JScrollPane();
        DebugViewer = new javax.swing.JPanel();
        DebugText = new javax.swing.JLabel();
        InfoViewerRoot = new javax.swing.JSplitPane();
        OutputPane = new javax.swing.JScrollPane();
        OutputView = new javax.swing.JEditorPane();
        ViewPane = new javax.swing.JSplitPane();
        StatusScrollPane = new javax.swing.JScrollPane();
        StatusTable = new javax.swing.JTable();
        MemoryPane = new javax.swing.JScrollPane();
        MemoryTable = new javax.swing.JTable();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.uniteduniverse.apps.bs1ide.BS1IDEApp.class).getContext().getResourceMap(BS1IDEView.class);
        HelpDialog.setTitle(resourceMap.getString("HelpDialog.title")); // NOI18N
        HelpDialog.setName("HelpDialog"); // NOI18N

        HelpScrollPane.setName("HelpScrollPane"); // NOI18N
        HelpScrollPane.setPreferredSize(new java.awt.Dimension(400, 700));

        HelpView.setBackground(resourceMap.getColor("HelpView.background")); // NOI18N
        HelpView.setContentType(resourceMap.getString("HelpView.contentType")); // NOI18N
        HelpView.setEditable(false);
        HelpView.setText(resourceMap.getString("HelpView.text")); // NOI18N
        HelpView.setName("HelpView"); // NOI18N
        HelpScrollPane.setViewportView(HelpView);

        javax.swing.GroupLayout HelpDialogLayout = new javax.swing.GroupLayout(HelpDialog.getContentPane());
        HelpDialog.getContentPane().setLayout(HelpDialogLayout);
        HelpDialogLayout.setHorizontalGroup(
            HelpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(HelpScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
        );
        HelpDialogLayout.setVerticalGroup(
            HelpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(HelpScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle(resourceMap.getString("BS1 IDE.title")); // NOI18N
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("BS1 IDE"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                Confirm(evt);
            }
        });

        Toolbars.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Toolbars.setName("Toolbars"); // NOI18N
        Toolbars.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        FileToolbar.setRollover(true);
        FileToolbar.setName("File Toolbar"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.uniteduniverse.apps.bs1ide.BS1IDEApp.class).getContext().getActionMap(BS1IDEView.class, this);
        NewToolbarBtn.setAction(actionMap.get("NewFile")); // NOI18N
        NewToolbarBtn.setIcon(resourceMap.getIcon("NewToolbarBtn.icon")); // NOI18N
        NewToolbarBtn.setText(resourceMap.getString("NewToolbarBtn.text")); // NOI18N
        NewToolbarBtn.setToolTipText(resourceMap.getString("NewToolbarBtn.toolTipText")); // NOI18N
        NewToolbarBtn.setFocusable(false);
        NewToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        NewToolbarBtn.setName("NewToolbarBtn"); // NOI18N
        NewToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        FileToolbar.add(NewToolbarBtn);

        OpenToolbarBtn.setAction(actionMap.get("Open")); // NOI18N
        OpenToolbarBtn.setIcon(resourceMap.getIcon("OpenToolbarBtn.icon")); // NOI18N
        OpenToolbarBtn.setText(resourceMap.getString("OpenToolbarBtn.text")); // NOI18N
        OpenToolbarBtn.setToolTipText(resourceMap.getString("OpenToolbarBtn.toolTipText")); // NOI18N
        OpenToolbarBtn.setFocusable(false);
        OpenToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        OpenToolbarBtn.setName("OpenToolbarBtn"); // NOI18N
        OpenToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        FileToolbar.add(OpenToolbarBtn);

        DownloadToolbarBtn.setAction(actionMap.get("Download")); // NOI18N
        DownloadToolbarBtn.setIcon(resourceMap.getIcon("DownloadToolbarBtn.icon")); // NOI18N
        DownloadToolbarBtn.setText(resourceMap.getString("DownloadToolbarBtn.text")); // NOI18N
        DownloadToolbarBtn.setFocusable(false);
        DownloadToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        DownloadToolbarBtn.setName("DownloadToolbarBtn"); // NOI18N
        DownloadToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        FileToolbar.add(DownloadToolbarBtn);

        SaveToolbarBtn.setAction(actionMap.get("Save")); // NOI18N
        SaveToolbarBtn.setIcon(resourceMap.getIcon("SaveToolbarBtn.icon")); // NOI18N
        SaveToolbarBtn.setText(resourceMap.getString("SaveToolbarBtn.text")); // NOI18N
        SaveToolbarBtn.setToolTipText(resourceMap.getString("SaveToolbarBtn.toolTipText")); // NOI18N
        SaveToolbarBtn.setFocusable(false);
        SaveToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        SaveToolbarBtn.setName("SaveToolbarBtn"); // NOI18N
        SaveToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        FileToolbar.add(SaveToolbarBtn);

        SaveAsToolbarBtn.setAction(actionMap.get("SaveAs")); // NOI18N
        SaveAsToolbarBtn.setIcon(resourceMap.getIcon("SaveAsToolbarBtn.icon")); // NOI18N
        SaveAsToolbarBtn.setText(resourceMap.getString("SaveAsToolbarBtn.text")); // NOI18N
        SaveAsToolbarBtn.setToolTipText(resourceMap.getString("SaveAsToolbarBtn.toolTipText")); // NOI18N
        SaveAsToolbarBtn.setFocusable(false);
        SaveAsToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        SaveAsToolbarBtn.setName("SaveAsToolbarBtn"); // NOI18N
        SaveAsToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        FileToolbar.add(SaveAsToolbarBtn);

        Toolbars.add(FileToolbar);

        DebugToolbar.setRollover(true);
        DebugToolbar.setName("Debug Toolbar"); // NOI18N

        GoToolbarBtn.setAction(actionMap.get("Go")); // NOI18N
        GoToolbarBtn.setIcon(resourceMap.getIcon("GoToolbarBtn.icon")); // NOI18N
        GoToolbarBtn.setText(resourceMap.getString("GoToolbarBtn.text")); // NOI18N
        GoToolbarBtn.setFocusable(false);
        GoToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        GoToolbarBtn.setName("GoToolbarBtn"); // NOI18N
        GoToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        DebugToolbar.add(GoToolbarBtn);

        DebugToolbarBtn.setAction(actionMap.get("Debug")); // NOI18N
        DebugToolbarBtn.setIcon(resourceMap.getIcon("DebugToolbarBtn.icon")); // NOI18N
        DebugToolbarBtn.setText(resourceMap.getString("DebugToolbarBtn.text")); // NOI18N
        DebugToolbarBtn.setToolTipText(resourceMap.getString("DebugToolbarBtn.toolTipText")); // NOI18N
        DebugToolbarBtn.setFocusable(false);
        DebugToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        DebugToolbarBtn.setName("DebugToolbarBtn"); // NOI18N
        DebugToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        DebugToolbar.add(DebugToolbarBtn);

        ToolbarSep1.setName("ToolbarSep1"); // NOI18N
        DebugToolbar.add(ToolbarSep1);

        ContinueBtn.setAction(actionMap.get("Continue")); // NOI18N
        ContinueBtn.setIcon(resourceMap.getIcon("ContinueBtn.icon")); // NOI18N
        ContinueBtn.setText(resourceMap.getString("ContinueBtn.text")); // NOI18N
        ContinueBtn.setToolTipText(resourceMap.getString("ContinueBtn.toolTipText")); // NOI18N
        ContinueBtn.setEnabled(false);
        ContinueBtn.setFocusable(false);
        ContinueBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ContinueBtn.setName("ContinueBtn"); // NOI18N
        ContinueBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        DebugToolbar.add(ContinueBtn);

        NextStepBtn.setAction(actionMap.get("Step")); // NOI18N
        NextStepBtn.setIcon(resourceMap.getIcon("NextStepBtn.icon")); // NOI18N
        NextStepBtn.setText(resourceMap.getString("NextStepBtn.text")); // NOI18N
        NextStepBtn.setToolTipText(resourceMap.getString("NextStepBtn.toolTipText")); // NOI18N
        NextStepBtn.setEnabled(false);
        NextStepBtn.setFocusable(false);
        NextStepBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        NextStepBtn.setName("NextStepBtn"); // NOI18N
        NextStepBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        DebugToolbar.add(NextStepBtn);

        Toolbars.add(DebugToolbar);

        SettingsToolbar.setRollover(true);
        SettingsToolbar.setName("SettingsToolbar"); // NOI18N

        ToolbarLabel1.setText(resourceMap.getString("ToolbarLabel1.text")); // NOI18N
        ToolbarLabel1.setName("ToolbarLabel1"); // NOI18N
        SettingsToolbar.add(ToolbarLabel1);

        try {
            BreakpointChar.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("*")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        BreakpointChar.setText(resourceMap.getString("BreakpointChar.text")); // NOI18N
        BreakpointChar.setAction(actionMap.get("SelectAll")); // NOI18N
        BreakpointChar.setName("BreakpointChar"); // NOI18N
        SettingsToolbar.add(BreakpointChar);

        SetToolbarBtn.setAction(actionMap.get("SetBreakpoint")); // NOI18N
        SetToolbarBtn.setIcon(resourceMap.getIcon("SetToolbarBtn.icon")); // NOI18N
        SetToolbarBtn.setText(resourceMap.getString("SetToolbarBtn.text")); // NOI18N
        SetToolbarBtn.setFocusable(false);
        SetToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        SetToolbarBtn.setName("SetToolbarBtn"); // NOI18N
        SetToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        SettingsToolbar.add(SetToolbarBtn);

        ResetToolbarBtn.setAction(actionMap.get("ResetBreakpoint")); // NOI18N
        ResetToolbarBtn.setIcon(resourceMap.getIcon("ResetToolbarBtn.icon")); // NOI18N
        ResetToolbarBtn.setText(resourceMap.getString("ResetToolbarBtn.text")); // NOI18N
        ResetToolbarBtn.setFocusable(false);
        ResetToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ResetToolbarBtn.setName("ResetToolbarBtn"); // NOI18N
        ResetToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        SettingsToolbar.add(ResetToolbarBtn);

        Toolbars.add(SettingsToolbar);

        HelpToolbar.setRollover(true);
        HelpToolbar.setName("HelpToolbar"); // NOI18N

        HelpToolbarBtn.setAction(actionMap.get("Help")); // NOI18N
        HelpToolbarBtn.setIcon(resourceMap.getIcon("HelpToolbarBtn.icon")); // NOI18N
        HelpToolbarBtn.setText(resourceMap.getString("HelpToolbarBtn.text")); // NOI18N
        HelpToolbarBtn.setFocusable(false);
        HelpToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        HelpToolbarBtn.setName("HelpToolbarBtn"); // NOI18N
        HelpToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        HelpToolbar.add(HelpToolbarBtn);

        AboutToolbarBtn.setAction(actionMap.get("About")); // NOI18N
        AboutToolbarBtn.setIcon(resourceMap.getIcon("AboutToolbarBtn.icon")); // NOI18N
        AboutToolbarBtn.setText(resourceMap.getString("AboutToolbarBtn.text")); // NOI18N
        AboutToolbarBtn.setFocusable(false);
        AboutToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        AboutToolbarBtn.setName("AboutToolbarBtn"); // NOI18N
        AboutToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        HelpToolbar.add(AboutToolbarBtn);

        Toolbars.add(HelpToolbar);

        MainPane.setBorder(null);
        MainPane.setDividerLocation(200);
        MainPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        MainPane.setName("MainPane"); // NOI18N
        MainPane.setPreferredSize(new java.awt.Dimension(800, 548));

        Workspace.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
        Workspace.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
        Workspace.setName("Workspace"); // NOI18N

        EditorPane.setBorder(null);
        EditorPane.setName("EditorPane"); // NOI18N

        SrcEditor.setColumns(20);
        SrcEditor.setFont(resourceMap.getFont("SrcEditor.font")); // NOI18N
        SrcEditor.setRows(5);
        SrcEditor.setText(resourceMap.getString("SrcEditor.text")); // NOI18N
        SrcEditor.setBorder(null);
        SrcEditor.setName("SrcEditor"); // NOI18N
        EditorPane.setViewportView(SrcEditor);

        Workspace.addTab(resourceMap.getString("EditorPane.TabConstraints.tabTitle"), resourceMap.getIcon("EditorPane.TabConstraints.tabIcon"), EditorPane); // NOI18N

        DebugViewerScrollPane.setBorder(null);
        DebugViewerScrollPane.setName("DebugViewerScrollPane"); // NOI18N

        DebugViewer.setBackground(resourceMap.getColor("DebugViewer.background")); // NOI18N
        DebugViewer.setName("DebugViewer"); // NOI18N

        DebugText.setFont(resourceMap.getFont("DebugText.font")); // NOI18N
        DebugText.setText(resourceMap.getString("DebugText.text")); // NOI18N
        DebugText.setName("DebugText"); // NOI18N

        javax.swing.GroupLayout DebugViewerLayout = new javax.swing.GroupLayout(DebugViewer);
        DebugViewer.setLayout(DebugViewerLayout);
        DebugViewerLayout.setHorizontalGroup(
            DebugViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(DebugViewerLayout.createSequentialGroup()
                .addComponent(DebugText)
                .addContainerGap(813, Short.MAX_VALUE))
        );
        DebugViewerLayout.setVerticalGroup(
            DebugViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(DebugViewerLayout.createSequentialGroup()
                .addComponent(DebugText)
                .addContainerGap(484, Short.MAX_VALUE))
        );

        DebugViewerScrollPane.setViewportView(DebugViewer);

        Workspace.addTab(resourceMap.getString("DebugViewerScrollPane.TabConstraints.tabTitle"), resourceMap.getIcon("DebugViewerScrollPane.TabConstraints.tabIcon"), DebugViewerScrollPane); // NOI18N

        MainPane.setTopComponent(Workspace);
        Workspace.getAccessibleContext().setAccessibleName(resourceMap.getString("Workspace.AccessibleContext.accessibleName")); // NOI18N

        InfoViewerRoot.setDividerLocation(250);
        InfoViewerRoot.setName("InfoViewerRoot"); // NOI18N

        OutputPane.setName("OutputPane"); // NOI18N

        OutputView.setEditable(false);
        OutputView.setFont(resourceMap.getFont("OutputView.font")); // NOI18N
        OutputView.setText(resourceMap.getString("OutputView.text")); // NOI18N
        OutputView.setToolTipText(resourceMap.getString("OutputView.toolTipText")); // NOI18N
        OutputView.setName("OutputView"); // NOI18N
        OutputPane.setViewportView(OutputView);

        InfoViewerRoot.setLeftComponent(OutputPane);

        ViewPane.setDividerLocation(250);
        ViewPane.setName("ViewPane"); // NOI18N

        StatusScrollPane.setName("StatusScrollPane"); // NOI18N

        StatusTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Information", "Value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        StatusTable.setColumnSelectionAllowed(true);
        StatusTable.setName("StatusTable"); // NOI18N
        StatusTable.getTableHeader().setReorderingAllowed(false);
        StatusScrollPane.setViewportView(StatusTable);
        StatusTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        StatusTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("StatusTable.columnModel.title0")); // NOI18N
        StatusTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("StatusTable.columnModel.title1")); // NOI18N

        ViewPane.setLeftComponent(StatusScrollPane);

        MemoryPane.setName("MemoryPane"); // NOI18N

        MemoryTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Address", "Value", "Character"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        MemoryTable.setToolTipText(resourceMap.getString("MemoryTable.toolTipText")); // NOI18N
        MemoryTable.setColumnSelectionAllowed(true);
        MemoryTable.setName("MemoryTable"); // NOI18N
        MemoryTable.getTableHeader().setReorderingAllowed(false);
        MemoryPane.setViewportView(MemoryTable);
        MemoryTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        MemoryTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("MemoryTable.columnModel.title0")); // NOI18N
        MemoryTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("MemoryTable.columnModel.title1")); // NOI18N
        MemoryTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("MemoryTable.columnModel.title2")); // NOI18N

        ViewPane.setRightComponent(MemoryPane);

        InfoViewerRoot.setRightComponent(ViewPane);

        MainPane.setRightComponent(InfoViewerRoot);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(Toolbars, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
            .addComponent(MainPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(Toolbars, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(MainPane, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void Confirm(java.awt.event.WindowEvent evt)//GEN-FIRST:event_Confirm
	{//GEN-HEADEREND:event_Confirm
		if ( ! edited)
		{
			System.exit(0);
		}
		if (JOptionPane.showConfirmDialog(null, "Are you sure?") == 0)
		{
			System.exit(0);
		}
	}//GEN-LAST:event_Confirm

	/**
	 * Set a new breakpoint char.
	 */
	@Action
	public void SetBreakpoint()
	{
		breakpoint = ((Character) BreakpointChar.getText().charAt(0)).toString();
		if (breakpoint == null)
		{
			breakpoint = " ";
		}
	}

	/**
	 * Reset breakpoint char to "#"
	 */
	@Action
	public void ResetBreakpoint()
	{
		breakpoint = "#";
		BreakpointChar.setText("#");
	}
	private File current = null;
	private boolean runningdebug = false;
	public String breakpoint = "#";
	private long timer = 0L;

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[])
	{
		java.awt.EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				new BS1IDEView().setVisible(true);
			}
		});
	}
	/**
	 * Is the document edited?
	 */
	private boolean edited = false;

	/**
	 * Disable debug buttons
	 */
	private void DisableDebugBtns()
	{
		ContinueBtn.setEnabled(false);
		NextStepBtn.setEnabled(false);
		DebugText.setText("<html><h2>Please click <u>Debug</u> to start debugging</h2><br /><b>Last debug session:</b><br />" + context.toString().replace("\n", "<br />"));
	}

	/**
	 * Enable debug buttons
	 */
	private void EnableDebugBtns()
	{
		ContinueBtn.setEnabled(true);
		NextStepBtn.setEnabled(true);
	}

	/**
	 * Update the Status table
	 */
	public void updateStatus()
	{
		Object[][] vals = new Object[5][2];
		long timespent = System.nanoTime() - timer;
		vals[0][0] = "Location X";
		vals[0][1] = context.LocationX + 1;

		vals[1][0] = "Location Y";
		vals[1][1] = context.LocationY + 1;

		vals[2][0] = "Last Opcode";
		vals[2][1] = context.codechar;

		vals[3][0] = "Memory Pointer";
		vals[3][1] = context.memorypointer;

		vals[4][0] = "Time Spent";
		vals[4][1] = String.format("%f seconds", (double) timespent / 1000000000D);

		StatusTable.setModel(
			new StatusTable(
			vals, new String[]
			{
				"Information", "Value"
			}));
	}

	/**
	 * Save the file
	 */
	@Action
	public void Save()
	{
		if (current != null)
		{
			try
			{
				BufferedWriter out = new BufferedWriter(new FileWriter(current.getAbsolutePath()));
				out.write(SrcEditor.getText());
				out.close();
				edited = false;
			}
			catch (IOException e)
			{
				e.printStackTrace(System.err);
				JOptionPane.showMessageDialog(null, "Unable to save file:\n" + e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		else
		{
			SaveAs();
		}
	}

	/**
	 * Get file's contents
	 * @param aFile The File object
	 * @return The contents of {@code aFile}
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 */
	public static String getContents(File aFile) throws FileNotFoundException, IOException
	{
		StringBuilder contents = new StringBuilder();
		BufferedReader input = new BufferedReader(new FileReader(aFile));
		String line = null; //not declared within while loop
		while ((line = input.readLine()) != null)
		{
			contents.append(line);
			contents.append(System.getProperty("line.separator"));
		}
		input.close();
		return contents.toString();
	}
	/**
	 * The default input and output handler.
	 */
	BS1Handler handler = new BS1Handler()
	{
		@Override
		public String InputCallback()
		{
			return JOptionPane.showInputDialog("Input prompt:");
		}

		@Override
		public void OutputCallback(int value)
		{
			char[] dummy = new char[1];
			dummy[0] = (char) value;
			OutputView.setText(OutputView.getText() + new String(dummy));
		}
	};
	public BrainSpace1 context = new BrainSpace1("", handler);

	/**
	 * Save the file under a new name
	 */
	@Action
	public void SaveAs()
	{
		JFileChooser fc = new JFileChooser();
		fc.addChoosableFileFilter(new BS1FileFilter());
		if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
		{
			current = fc.getSelectedFile();
			try
			{
				BufferedWriter out = new BufferedWriter(new FileWriter(current.getAbsolutePath()));
				out.write(SrcEditor.getText());
				out.close();
				edited = false;
			}
			catch (IOException e)
			{
				e.printStackTrace(System.err);
				JOptionPane.showMessageDialog(null, "Unable to save file:\n" + e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Prompt to create a new file
	 * @return Is a new file created?
	 */
	@Action
	public boolean NewFile()
	{
		if (edited == false)
		{
			OutputView.setText("");
			SrcEditor.setText("");
			current = null;
			return true;
		}
		else if (JOptionPane.showConfirmDialog(null, "Are you sure?") == 0 && edited == true)
		{
			OutputView.setText("");
			SrcEditor.setText("");
			current = null;
			edited = false;
			return true;
		}
		return false;
	}

	/**
	 * Update the debug viewer
	 */
	public void updateDebugStatus()
	{
		String txt = "<html><pre>";
		for (int y = 0; y < context.code.size(); y ++)
		{
			if (y == context.LocationY)
			{
				for (int x = 0; x < context.width(); x ++)
				{
					try
					{
						if (x == context.LocationX)
						{
							txt += "<b bgcolor='red' style='background-color:red;'>" + ((Character) context.code.get(y).charAt(x)).toString().replace("<", "&lt;") + "</b>";
						}
						else
						{
							txt += ((Character) context.code.get(y).charAt(x)).toString().replace("<", "&lt;");
						}
					}
					catch (StringIndexOutOfBoundsException e)
					{
						if (x == context.LocationX)
						{
							txt += "<b bgcolor='red' style='background-color:red;'>&nbsp;</b>";
						}
						else
						{
							txt += "&nbsp;";
						}
					}
				}
			}
			else
			{
				txt += context.code.get(y).replace("<", "&lt;");
			}
			txt += "\n";
		}
		DebugText.setText(txt + "</pre>");
	}

	/**
	 * Update the memory table
	 */
	public void updateTable()
	{
		Object[][] vals = new Object[context.memory.size()][3];

		char[] dummy = new char[1];
		for (int i = 0; i < context.memory.size(); i ++)
		{
			dummy[0] = (char) (int) context.memory.get(i);
			vals[i][0] = i;
			vals[i][1] = context.memory.get(i);
			vals[i][2] = new String(dummy);
		}

		MemoryTable.setModel(
			new MemoryTable(
			vals, new String[]
			{
				"Address", "Value", "Character"
			}));
	}

	/**
	 * Start running w/out debug
	 */
	@Action
	public void Go()
	{
		timer = System.nanoTime();
		OutputView.setText("");
		context = new BrainSpace1(SrcEditor.getText(), handler);
		context.Run();
		Update();
	}

	/**
	 * Prompt to open a file
	 */
	@Action
	public void Open()
	{
		if (edited)
		{
			if ( ! NewFile())
			{
				return;
			}
		}
		JFileChooser fc = new JFileChooser();
		fc.addChoosableFileFilter(new BS1FileFilter());
		if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
		{
			current = fc.getSelectedFile();
			try
			{
				SrcEditor.setText(getContents(current));
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace(System.err);
				JOptionPane.showMessageDialog(null, "Unable to open file:\n " + e, "Error", JOptionPane.ERROR_MESSAGE);
			}
			catch (IOException e)
			{
				e.printStackTrace(System.err);
				JOptionPane.showMessageDialog(null, "IO Error:\n " + e, "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Start debugging
	 */
	@Action
	public void Debug()
	{
		timer = System.nanoTime();
		runningdebug = true;
		OutputView.setText("");
		context = new BrainSpace1(SrcEditor.getText(), handler);
		Workspace.setSelectedComponent(DebugViewerScrollPane);
		EnableDebugBtns();
		Update();

		while (true)
		{
			if ( ! context.Go())
			{
				Update();
				DisableDebugBtns();
				runningdebug = false;
				break;
			}
			if (context.codechar.equals(breakpoint))
			{
				Update();
				break;
			}
		}
	}

	@Action
	public void Continue()
	{
		if (runningdebug)
		{
			EnableDebugBtns();
			while (true)
			{
				if ( ! context.Go())
				{
					DisableDebugBtns();
					Update();
					runningdebug = false;
					break;
				}
				if (context.codechar.equals(breakpoint))
				{
					Update();
					break;
				}
			}
		}
	}

	@Action
	public void Step()
	{
		if (runningdebug && ( ! context.Go()))
		{
			DisableDebugBtns();
			runningdebug = false;
		}
		Update();
	}

	@Action
	public void About()
	{
		BS1IDEAboutBox a = new BS1IDEAboutBox(this);
		a.setVisible(true);
	}

	/**
	 * Show the help dialog
	 */
	@Action
	public void Help()
	{
		HelpDialog.setVisible(true);
		HelpDialog.setSize(400, 700);
	}

	@Action
	public void Download()
	{
		if (JOptionPane.showConfirmDialog(null, "Unsaved work will be lost. Are you sure?", "Download", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == 0)
		{
			String data = "";
			try
			{
				// Send data
				URL url = new URL(JOptionPane.showInputDialog("Enter URL:", ""));
				URLConnection conn = url.openConnection();
				conn.setDoOutput(true);
				conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; fr; rv:1.9b5) Gecko/2008032620 Firefox/3.0b5");
				OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
				wr.write(data);
				wr.flush();

				// Get the response
				BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line;
				while ((line = rd.readLine()) != null)
				{
					data += line;
				}
				wr.close();
				rd.close();
				SrcEditor.setText(data);
			}
			catch (Exception e)
			{
				e.printStackTrace(System.err);
				JOptionPane.showMessageDialog(null, "Unable to download file:\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	private class StatusTable extends DefaultTableModel
	{
		public StatusTable(Object[][] data, Object[] columnNames)
		{
			super(data, columnNames);
		}
		Class[] types = new Class[]
		{
			String.class, Integer.class
		};

		@Override
		public Class getColumnClass(int columnIndex)
		{
			try
			{
				return types[columnIndex];
			}
			catch (Exception e)
			{
				e.printStackTrace(System.err);
				return null;
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex)
		{
			return false;
		}
	}

	private class MemoryTable extends DefaultTableModel
	{
		public MemoryTable(Object[][] data, Object[] columnNames)
		{
			super(data, columnNames);
		}
		Class[] types = new Class[]
		{
			Integer.class, Integer.class, String.class
		};

		@Override
		public Class getColumnClass(int columnIndex)
		{
			try
			{
				return types[columnIndex];
			}
			catch (Exception e)
			{
				e.printStackTrace(System.err);
				return null;
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex)
		{
			return false;
		}
	}

	private class BS1FileFilter extends javax.swing.filechooser.FileFilter
	{
		public BS1FileFilter()
		{
		}

		//http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html
		public String getExtension(File f)
		{
			String ext = null;
			String s = f.getName();
			int i = s.lastIndexOf('.');
			if (i > 0 && i < s.length() - 1)
			{
				ext = s.substring(i + 1).toLowerCase();
			}
			return ext;
		}

		@Override
		public boolean accept(File f)
		{
			String ext = getExtension(f);
			if (f.isDirectory())
			{
				return true;
			}
			if (ext.equals("bs1"))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		@Override
		public String getDescription()
		{
			return "BS1 source files";
		}
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton AboutToolbarBtn;
    public javax.swing.JFormattedTextField BreakpointChar;
    public javax.swing.JButton ContinueBtn;
    public javax.swing.JLabel DebugText;
    public javax.swing.JToolBar DebugToolbar;
    public javax.swing.JButton DebugToolbarBtn;
    public javax.swing.JPanel DebugViewer;
    public javax.swing.JScrollPane DebugViewerScrollPane;
    public javax.swing.JButton DownloadToolbarBtn;
    public javax.swing.JScrollPane EditorPane;
    public javax.swing.JToolBar FileToolbar;
    public javax.swing.JButton GoToolbarBtn;
    public javax.swing.JDialog HelpDialog;
    public javax.swing.JScrollPane HelpScrollPane;
    public javax.swing.JToolBar HelpToolbar;
    public javax.swing.JButton HelpToolbarBtn;
    public javax.swing.JEditorPane HelpView;
    public javax.swing.JSplitPane InfoViewerRoot;
    public javax.swing.JSplitPane MainPane;
    public javax.swing.JScrollPane MemoryPane;
    public javax.swing.JTable MemoryTable;
    public javax.swing.JButton NewToolbarBtn;
    public javax.swing.JButton NextStepBtn;
    public javax.swing.JButton OpenToolbarBtn;
    public javax.swing.JScrollPane OutputPane;
    public javax.swing.JEditorPane OutputView;
    public javax.swing.JButton ResetToolbarBtn;
    public javax.swing.JButton SaveAsToolbarBtn;
    public javax.swing.JButton SaveToolbarBtn;
    public javax.swing.JButton SetToolbarBtn;
    public javax.swing.JToolBar SettingsToolbar;
    public javax.swing.JTextArea SrcEditor;
    public javax.swing.JScrollPane StatusScrollPane;
    public javax.swing.JTable StatusTable;
    public javax.swing.JLabel ToolbarLabel1;
    public javax.swing.JToolBar.Separator ToolbarSep1;
    public javax.swing.JPanel Toolbars;
    public javax.swing.JSplitPane ViewPane;
    public javax.swing.JTabbedPane Workspace;
    // End of variables declaration//GEN-END:variables
}
